import axios from "axios";
import {msg} from '@/composables/util.js'
import {mainStore} from '@/store/index'


const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
  });


  // 添加请求拦截器
service.interceptors.request.use(
    function (config) {
      // 往header头自动添加token
      const token = localStorage.getItem('token');
      if (token) {
        config.headers["token"] = token;
      }
  
      return config;
    },
    function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );

// 添加响应拦截器
service.interceptors.response.use(
    function (response) {
      // 对响应数据做点什么
      return response.data.data;
    },
    function (error) {
      const message = error.response.data.msg || "请求失败";
      
      if (error.response.data.errorCode == 401) {
        // localStorage.removeItem('token')
        const store=mainStore();
        
        store.logout().finally(() => location.reload());
      }
  
      msg(message, "error");
  
      return Promise.reject(error);
    }
  );
export default service;
